<script>
import { User, Lock, Message } from "@element-plus/icons-vue";
import { ref } from "vue";
import api from "../api/API.js";
import { definedUser } from "../store/store.js";

export default {
  name: "Login",
  components: {
    User,
    Lock,
    Message,
  },
  data() {
    return {
      user: {
        username: "",
        email: "",
        password: "",
        isAgree: false,
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "用户名必须是5-10位 的字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "邮箱格式不正确",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^\S{6,15}$/,
            message: "密码必须是6-15位 的非空字符",
            trigger: "blur",
          },
        ],
        isAgree: [
          {
            validator: (rule, value, callback) => {
              value ? callback() : callback(new Error("请勾选用户协议"));
            },
          },
        ],
      },
      isRegister: false,
      form: ref(),
    };
  },
  methods: {
    handleLogin() {
      const user = {
        username: this.user.username,
        password: this.user.password,
        email: this.user.email,
      };

      api
        .loginUser(this.user)
        .then((response) => {
          // 登录成功，处理响应
          if (response.data.status == 200) {
            console.log(response);
            // alert(response.data.message);
            this.$router.push("home");
            const token = response.data.data.token;
            definedUser().setToken(token);
            api.getUserInfo(response.data.data.userId).then((response) => {
              if (response.data.status == 200) {
                let userInfo = response.data.data;
                definedUser().setUserInformation(userInfo);
              }
            });
          }
          console.log(response.data);
        })
        .catch((error) => {
          // 登录失败，处理错误
          this.$message.error("密码错误，请重新输入！");
          console.error(error);
        });
    },
    handleRegister() {
      // 处理注册逻辑

      api
        .registerUser(this.user)
        .then((response) => {
          if (response.data.status != 200) {
            console.log(response);
            alert(response.data.message);
            return;
          }

          // 注册成功，处理响应
          this.user.id = response.data.id;
          this.userInfo = user;
          this.isLoggedIn = true;
          this.dialogFormVisible = false;
        })
        .catch((error) => {
          // 注册失败，处理错误

          alert(error.message);
          console.error(error);
        });

      this.$refs.form.validate((isOK) => {
        if (isOK) {
          this.$router.push("/home");
          alert("注册成功");
        }
      });
    },
  },
};
</script>

<template>
  <router-view></router-view>

  <el-row class="login-page">
    <img
      src="../img/M.jpg"
      alt="登录注册背景图"
      style="height: 100vh; width: 100%"
    />
    <div class="my_title">网上购书商城</div>
    <el-card shadow="always">
      <el-row class="form-container">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="20" :offset="3" class="form">
          <!-- 注册表单 -->
          <el-form
            ref="form"
            :rules="loginRules"
            size="large"
            autocomplete="off"
            :model="user"
            v-if="isRegister"
          >
            <el-form-item>
              <h1 style="font-family: 'Microsoft YaHei'">注册</h1>
            </el-form-item>
            <el-form-item prop="username">
              <el-input
                :prefix-icon="User"
                placeholder="请输入用户名"
                v-model="user.username"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="email">
              <el-input
                :prefix-icon="User"
                placeholder="请输入邮箱"
                v-model="user.email"
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :prefix-icon="Lock"
                type="password"
                v-model="user.password"
                placeholder="请输入密码"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                class="button"
                type="primary"
                auto-insert-space
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
            <el-form-item class="flex">
              <el-link
                type="info"
                :underline="false"
                @click="isRegister = false"
              >
                ← 返回
              </el-link>
            </el-form-item>
          </el-form>

          <!-- 登录表单 -->
          <el-form
            ref="form"
            size="large"
            :rules="loginRules"
            :model="user"
            autocomplete="off"
            v-else
          >
            <el-form-item>
              <h1 style="font-family: 'Microsoft YaHei'">登录</h1>
            </el-form-item>
            <el-form-item prop="email">
              <el-input
                :prefix-icon="User"
                placeholder="请输入用户邮箱"
                v-model="user.email"
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                v-model="user.password"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="isAgree" class="flex">
              <el-checkbox v-model="user.isAgree">用户平台使用协议</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button
                class="button"
                type="primary"
                @click="handleLogin"
                auto-insert-space
                >登录</el-button
              >
            </el-form-item>
            <el-form-item class="flex">
              <el-link
                type="info"
                :underline="false"
                @click="isRegister = true"
              >
                注册 →
              </el-link>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
  .form-container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .my_title {
    position: absolute;
    left: 35%;
    transform: translate(-50%, -50%);
    margin-top: -250px;
    margin-left: 15%;
    float: left;

    color: rgb(248, 250, 249);
    font-size: 50px;
    text-align: center;
    line-height: 200px;
    text-shadow: 0px 1px 2px #a0baaa, 0px -5px 6px rgb(149, 214, 182),
      0px -9px 14px rgb(135, 150, 140), 0px -11px 18px rgb(116, 179, 67);
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}

.el-card {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 450px;
  width: 400px;
  border-radius: 20px;
  background-color: rgba(255, 255, 255, 0.4);
  border: 1px solid rgba(0, 0, 0, 0.1);
  opacity: 1;
  margin-top: -500px;
}
</style>
